package com.pym.bs.service.Impl;

import com.pym.bs.dao.DemosMapper;
import com.pym.bs.domain.Demos;
import com.pym.bs.dto.DemosDTO;
import com.pym.bs.service.UploadService;
import com.pym.bs.utils.ResultVOUtils;
import com.pym.bs.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

@Service
public class UploadServiceImpl implements UploadService {

    @Resource
    private DemosMapper demosMapper;

    @Override
    public ResultVO<Demos> save(DemosDTO demosDTO) throws IOException {
        if (demosDTO.getFile() != null) {
            for (int i = 0; i < demosDTO.getFile().length; i++) {
                Random rand = new Random();
                int random = rand.nextInt();

                String fileName = demosDTO.getFile()[i].getOriginalFilename();
                demosDTO.setUpload(fileName);
                String filePath = "D:/Picture";
                String name = random + fileName;
                File dest = new File(new File(filePath).getAbsolutePath() + "/" + name);
                demosDTO.getFile()[i].transferTo(dest);

                demosDTO.setUpload(name);
                System.out.println(name);
            }
        }

//        if (demosDTO.getEsign() != null || demosDTO.getEsign() != "") {
////            String esignName = demosDTO.getEsign().substring(22,42);
//                System.out.println(demosDTO.getEsign());
//            BASE64Decoder decoder = new BASE64Decoder();
//            byte[] b = decoder.decodeBuffer(demosDTO.getEsign());
//            for (int i =0;i<b.length;i++) {
//                if (b[i]<0) {
//                    b[i]+=256;
//                }
//            }
//            String path = "D:/Picture";
//            OutputStream out = new FileOutputStream(path);
//            out.write(b);
//            out.flush();
//            out.close();
//
//        }

        Demos demos = new Demos();
        Date date = new Date();
        demosDTO.setCreateTime(date);
        BeanUtils.copyProperties(demosDTO,demos);
//        demosMapper.insertSelective(demos);
        return ResultVOUtils.success();
    }
}
